package com.cnemc.docker.pool;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.cnemc.docker.config.DockerProperties;

public class DockerClientPool {
    private final GenericObjectPool<DockerClient> pool;

    public DockerClientPool(DockerProperties properties) {
        GenericObjectPoolConfig<DockerClient> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(properties.getMaxTotalConnections());
        poolConfig.setMaxIdle(properties.getMaxIdle());
        poolConfig.setMinIdle(properties.getMinIdle());
        poolConfig.setTestOnBorrow(true);
        pool = new GenericObjectPool<>(new DockerClientFactory(properties), poolConfig);
    }

    public DockerClient borrowObject() throws Exception {
        return pool.borrowObject();
    }

    public void returnObject(DockerClient client) {
        pool.returnObject(client);
    }

    private static class DockerClientFactory extends BasePooledObjectFactory<DockerClient> {
        private final DockerProperties properties;

        public DockerClientFactory(DockerProperties properties) {
            this.properties = properties;
        }

        @Override
        public DockerClient create() {
            DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost(properties.getHost())
                    .build();
            return DockerClientBuilder.getInstance(config).build();
        }

        @Override
        public PooledObject<DockerClient> wrap(DockerClient client) {
            return new DefaultPooledObject<>(client);
        }
    }
} 